import json
import re


# 提取数据的类
class DataHanlder:
    # 构造方法
    def __int__(self):
        pass

    # 获取用户名
    def getUserName(self, list):
        user_name = ''
        line_no = 0
        start = False
        temp_top = 0
        data_list = []
        first_name_list = self.__read_json('a.json')
        for item in list:
            words = item['words']  # item代表从百度api识图的结果
            if '订单详情' in words:  # 从订单详情开始读取识别出来的内容
                start = True
            if start:
                location = item['location']    # 定位图片的左上角开始一行一行的进行识别
                top = location['top']
                height = location['height']

                if temp_top != 0 and (top - temp_top) > height:
                    line_no = line_no + 1
                    # print("第" + str(line_no) + "行" + str(data_list))
                    re = self.check(data_list, '成人票') or self.check(data_list, '学生票') or self.check(data_list, '乘客')
                    # print('re: '+ str(re))
                    if re:
                        break
                    data_list.clear()
                temp_top = top
                data_list.append(words)

        for item in data_list:
            if '身份证' not in item and '学生票' not in item:
                # print(item)
                if self.__is_name(first_name_list, item):
                    user_name = item
                    break
            else:
                item = str(item).replace("（", "(")
                sp = str(item).split("(")
                if (len(sp) > 0) and self.__is_name(first_name_list, sp[0]):
                    user_name = sp[0]
                    break
            # if user_name:
            #     item = str(item).replace("（", "(")
            #     sp = str(item).split("(")
            #     if (len(sp) > 0):
            #         user_name = item
        return user_name

    # 获取订单号
    def get_order_no(self, list):
        data_list = []
        line_no = 0
        start = False
        temp_top = 0
        for item in list:
            words = item['words']
            if '订单详情' in words:  # 从订单详情开始读取识别出来的内容
                # print("第" + str(lineNo) + "行")
                start = True
            if start:
                location = item['location']
                top = location['top']
                height = location['height']

                # print("top - temp_top = " + str(top - temp_top))
                # print(temp_top != 0)
                # print((top - temp_top) > height)

                if temp_top != 0 and (top - temp_top) > height:
                    # print(data_list)
                    line_no = line_no + 1
                    # print("第" + str(line_no) + "行" + str(data_list))
                    re = self.check(data_list, '单号') or self.check(data_list, '票号')
                    # print('re: '+ str(re))
                    if re:
                        break
                    data_list.clear()
                temp_top = top
                # print(words)
                # print(location)
                data_list.append(words)
        # print("data_list: " + str(data_list))
        for no in data_list:
            no = str(no).replace("：", ":")
            if ":" in no:
                arr = no.split(":")
                if len(arr) == 2:
                    return arr[1]
            else:
                return data_list[1]

    def get_point(self, list):
        data_list = []
        line_no = 0
        start = False
        temp_top = 0
        for item in list:
            words = item['words']
            if '订单详情' in words:  # 从订单详情开始读取识别出来的内容
                start = True
            if start:
                location = item['location']
                top = location['top']
                height = location['height']
                if temp_top != 0 and (top - temp_top) > height:
                    line_no = line_no + 1
                    print("第" + str(line_no) + "行" + str(data_list))
                    res = self.check_address_point(data_list)
                    # print('re: '+ str(re))
                    if res:
                        break
                    data_list.clear()
                temp_top = top
                data_list.append(words)
        # print(data_list)
        # 匹配纯汉子的正则
        hz_reg = r'^[\u4e00-\u9fa5]{0,}$'
        s = data_list[0]
        e = data_list[len(data_list) - 1]
        re_data = []
        p = re.search(hz_reg, e)
        if p is not None:
            return [s, e]
        else:
            for o in data_list:
                if re.search(hz_reg, o) is not None and len(re_data) < 2:
                    re_data.append(o)
        return re_data

    # 获取出发和到站 时间
    def get_time(self, list):
        data_list = []
        line_no = 0
        start = False
        temp_top = 0
        # 匹配时间的正则
        time_re = r'^(0\d|1\d|2[0-4]):[0-5]\d$'
        for item in list:
            words = item['words']
            if '订单详情' in words:  # 从订单详情开始读取识别出来的内容
                start = True
            if start:
                location = item['location']
                top = location['top']
                height = location['height']
                if temp_top != 0 and (top - temp_top) > height:
                    line_no = line_no + 1
                    # print("第" + str(line_no) + "行" + str(data_list))
                    march_ct = 0
                    for o in data_list:
                        pattern = re.search(time_re, o)
                        if pattern is not None:
                            march_ct = march_ct + 1
                    if march_ct == 2:
                        break
                    data_list.clear()
                temp_top = top
                data_list.append(words)
        re_list = []
        for dt in data_list:
            if re.search(time_re, dt) is not None:
                re_list.append(dt)
        return re_list

    # 获取出发日期
    def get_date(self, list):
        data_list = []
        line_no = 0
        start = False
        temp_top = 0
        # 匹配日期正则
        date_re = r'(20\d{2})(-|\s|年|/)?((0\d)|(1[0-2]))(-|/|\s|月)?([0-3]\d)(\s?|日)(\s?)((星期|周)(一|二|三|四|五|六|日|天))'
        for item in list:
            # print(item)
            words = item['words']
            if '订单详情' in words:  # 从订单详情开始读取识别出来的内容
                start = True
            if start:
                location = item['location']
                top = location['top']
                height = location['height']
                if temp_top != 0 and (top - temp_top) > height:
                    # print(data_list)
                    line_no = line_no + 1
                    # print("第" + str(line_no) + "行" + str(data_list))
                    ret = False
                    for o in data_list:
                        pattern = re.search(date_re, o)
                        if pattern is not None:
                            ret = True

                    if ret:
                        break
                    data_list.clear()
                temp_top = top
                data_list.append(words)
        # print(data_list)
        for dt in data_list:
            if re.search(date_re, dt) is not None:
                return re.search(date_re, dt).group()

    # 获取车次
    def get_car_no(self, list):
        # 车次正则表达式 大写字母+数字3位或四位
        car_no_reg = r'^[A-Z]\d{3}(\d?)'
        for item in list:
            words = item['words']
            p = re.search(car_no_reg, words)
            if p is not None:
                return p.group()

    # 获取价格
    def get_price(self, list):
        # 价格正则 ¥或者￥开头数字+小数点+数字
        car_no_reg = r'¥|￥\d{0,}\.?\d{0,}'
        for item in list:
            words = item['words']
            # print(words)
            p = re.search(car_no_reg, words)
            if p is not None:
                return p.group()

    """
     判断数组里面是否包含某个字符
    """

    def check(self, list, s):
        for o in list:
            if s in o:
                return True

    def check_address_point(self, list):
        time_re = r'^(0\d|1\d|2[0-4]):[0-5]\d$'
        for o in list:
            if re.search(time_re, o) is not None:
                return False
            if '经停站' in o or '时刻表' in o or '历时' in o:
                return True

    # 读取json文件 获取a.json 里面的百家姓
    def __read_json(self, f):
        import os
        path = str(os.getcwd()) + '/mysite/' + f
        with open(path, 'r', encoding='UTF-8') as jsonfile:
            jsonText = jsonfile.read()
        return json.loads(jsonText)

    # 通过姓氏判断读取的用户名是否有效
    def __is_name(self, list, name):
        for n in list:
            if str(name).startswith(n):
                return True
